/*
 * 项   目：website-template
 * 作   者：LuoYiMin
 * 邮   箱：1725990142@qq.com
 * 创建时间：2018/9/30 10:04
 */
package com.roin.util.code.generator.util;

import org.apache.commons.text.StringEscapeUtils;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * StringUtils
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {
    /**
     * 首字母转大写
     */
    public static String toUpperCaseFirstChar(String s){
        if (isBlank(s))
            return s;
        if(Character.isUpperCase(s.charAt(0)))
            return s;
        else{
            char[] chars = s.toCharArray();
            if (chars[0] >= 'a' && chars[0] <= 'z') {
                chars[0] = (char)(chars[0] - 32);
            }
           return  new String(chars);
        }
    }
    /**
     * 首字母转大写
     */
    public static String toLowerCaseFirstChar(String s){
        if (isBlank(s))
            return s;
        if(Character.isLowerCase(s.charAt(0)))
            return s;
        else{
            char[] chars = s.toCharArray();
            if (chars[0] >= 'A' && chars[0] <= 'Z') {
                chars[0] = (char)(chars[0] + 32);
            }
           return  new String(chars);
        }
    }



    /**下划线转驼峰*/
    public static String lineToHump(String str){
        str = str.toLowerCase();
        Matcher matcher = Pattern.compile("_(\\w)").matcher(str);
        StringBuffer sb = new StringBuffer();
        while(matcher.find()){
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
    /**驼峰转下划线,效率比上面高*/
    public static String humpToLine(String str) {
        Matcher matcher = Pattern.compile("[A-Z]").matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        if (sb.indexOf("_")==0 && str.indexOf("_")!=0)
            sb.deleteCharAt(0);
        return sb.toString();
    }

    /**
     * 是否为数字
     * 包括负数、小数、整数
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
//        Pattern pattern = Pattern.compile("[0-9]*");
//        Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]+");
        Pattern pattern = Pattern.compile("^(\\-|\\+)?\\d+(\\.\\d+)?$");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 格式化字符串
     * <p>
     * 例：formatString("xxx{0}bbb",1) = xxx1bbb
     *
     * @param str
     * @param params
     * @return
     */
    public static String formatString(String str, String... params) {
        for (int i = 0; i < params.length; i++) {
            str = str.replace("{" + i + "}", params[i] == null ? "" : params[i]);
        }
        return str;
    }


    /**
     * 替换掉HTML标签方法
     */
    public static String stripHtml(String html) {
        if (isBlank(html)) {
            return "";
        }
        String regEx = "<.+?>";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(html);
        String s = m.replaceAll("");
        return s;
    }

    /**
     * 缩略字符串（不区分中英文字符）
     * * @param str 目标字符串
     * * @param length 截取长度
     * * @return
     */
    public static String abbr(String str, int length) {
        if (str == null) {
            return "";
        }
        try {
            StringBuilder sb = new StringBuilder();
            int currentLength = 0;
            for (char c : stripHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
                currentLength += String.valueOf(c).getBytes("GBK").length;
                if (currentLength <= length - 3) {
                    sb.append(c);
                } else {
                    sb.append("...");
                    break;
                }
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 将身份证的中间部分转成*号
     * @param idNumber 身份证号
     * @return
     */
    public static String hideIdCardNum(String idNumber) {
        if (isEmpty(idNumber))
            return "";
        return idNumber.replaceAll("(\\d{4})\\d{10}(\\w{4})","$1*****$2");
    }
    /**
     * 将手机号的中间部分转成*号
     * @param phone 手机号
     * @return
     */
    public static String hidePhone(String phone) {
        if (isEmpty(phone))
            return "";
        return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
    }
    /**
     * 将姓名的中间部分转成*号
     * @param name 姓名
     * @return
     */
    public static String hideName(String name) {
        if (isEmpty(name))
            return "";
        if(name.length() == 2){
            name =  name.replaceFirst(name.substring(1),"*");
        }else if (name.length() > 2) {
            name =  name.replaceFirst(name.substring(1,name.length()-1) ,"*");
        }
        return  name;
    }

    /**
     * 是否为正确的手机号
     * @param phone
     * @return
     */
    public static boolean isPhone(String phone) {
        Pattern pattern = Pattern.compile("^(13[0-9]|14[0-9]|15[0-9]|166|17[0-9]|18[0-9]|19[8|9])\\d{8}$");
        Matcher isPhone = pattern.matcher(phone);
        return isPhone.matches();
    }
    final static String sources1 = "0123456789"; // 加上一些字母，就可以生成pc站的验证码了
    final static String sources2 = "0123456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ"; // 加上一些字母，就可以生成pc站的验证码了
    /**
     * 生成随机字符串
     * @param length 长度
     * @param hasChar 是否有字母
     */
    public static String generateCode(int length,boolean hasChar){
        Random rand = new Random();
        StringBuffer flag = new StringBuffer();
        String sources;
        if (hasChar)
            sources = sources2;
        else
            sources = sources1;
        for (int j = 0; j < length; j++)
        {
            flag.append(sources.charAt(rand.nextInt(sources.length())) + "");
        }
        return flag.toString();
    }

    private static final String DEFAULT_DATE_PATTERN="yyyy-MM-dd HH:mm:ss";

    /**
     * 格式化日期-yyyy-MM-dd HH:mm:ss
     * @param date 日期
     * @return
     */
    public static String dateFormat(Date date) {
        return dateFormat(date,DEFAULT_DATE_PATTERN);
    }
    /**
     * 格式化日期
     * @param date 日期
     * @param pattern 格式
     * @return
     */
    public static String dateFormat(Date date, String pattern) {
        if (date==null)
            return "";
        if (isEmpty(pattern))
            pattern=DEFAULT_DATE_PATTERN;
        return new SimpleDateFormat(pattern).format(date);
    }
}
